﻿package com.snake{
	import com.snake.core.*;
	import effects.*;
	import flash.events.*;
	import flash.ui.Keyboard;
	import flash.display.MovieClip;
	import flash.media.*;
	public class Engine extends MovieClip {
		private var dir="left";
		private var food=null;
		private var blank=null;
		private var gui:Gui=null;
		public function Engine() {
			Game.fx_eat_food = new EatFoodFX();
			Game.fx_death = new DeathFX();
			Game.main_stage=stage;
			Game.goto=gotoAndStop;
			stop();
		}
		public function start_GUI(type) {
			gui=new Gui(type);
		}
		public function start() {
			start_GUI("game");
			addEventListener(Event.ENTER_FRAME, run);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, key_Down);
			Game.map.reset();
		}
		public function key_Down(e:KeyboardEvent) {
			switch (e.keyCode) {
				case Keyboard.LEFT :
					dir="left";
					break;
				case Keyboard.UP :
					dir="up";
					break;
				case Keyboard.RIGHT :
					dir="right";
					break;
				case Keyboard.DOWN :
					dir="down";
					break;
			}
		}
		public function init() {
			stage.frameRate=gui.RETURN_FRAME_RATE;
			stage.focus=stage;

			Game.map=new Map(Constants.MAIN_TILE_WIDTH, Constants.MAIN_TILE_HEIGHT, Constants.STAGE_WIDTH, Constants.STAGE_HEIGHT);
			Game.snake=new SnakeInstance(stage.stageWidth/2,stage.stageHeight/2,Constants.START_BLOCKS);
			Game.food=new FoodInstance();
		}
		public function handle_lost() {
			Game.destroy_elements();
			removeEventListener(Event.ENTER_FRAME, run);
			start_GUI("end");
			Game.score=0;
		}
		private function run(e:Event) {
			if (Game.snake.cur_dir=="left"&&dir=="right") {
				dir="left";
			}
			if (Game.snake.cur_dir=="right"&&dir=="left") {
				dir="right";
			}
			if (Game.snake.cur_dir=="up"&&dir=="down") {
				dir="up";
			}
			if (Game.snake.cur_dir=="down"&&dir=="up") {
				dir="down";
			}
			Game.snake.move(dir);
			var food=Game.map.getTile(Game.snake.index).isFood;
			if (food) {
				Game.fx_eat_food.play();
				Game.food.reset();
				Game.food.set_r_pos();
				
				Game.snake.addBlock();
				Game.inc_score();
				score_txt.text="Score: "+Game.score;
			}
			if (Game.lost()) {
				Game.fx_death.play();
				gotoAndStop(3);
			}
			trace("Snake index: "+Game.snake.index);
		}
	}
}
